package com.zhongkai.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.zhongkai.CookieUtils;
import com.zhongkai.app.service.PowerSyetemService;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Chinaset;
import com.zhongkai.model3.MenusRole;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * web拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = Logger.getLogger(LoginInterceptor.class);
    /*            "/set_model/add", //添加产品
                        "/set_model/list", //产品列表
                        "/supplier/add", //供应商添加
                        "/supplier/list", //供应商列表
                                    "/app_user/add",
                "/app_user/update",
                "/app_user/remove",
                "/app_user/list",
                "/section/",
                "/indent_service/",
                "/sell/",


                        */

    private static final String[] allowUrls = {//不需要登录可以访问的接口
            "/web/login", //登录
            "/web/registered", //注册
            "/device/device_add", //添加设备

            "/address/province", //获取全部省份
            "/address/city",
            "/address/country",
            "/address/town",
            //      "/pic/upload",
            "/big_date/basic",
            "/big_date/unit_list",
            "/big_date/analyze",
            "/intime/list",
            "/like/",
            "/big_date/",
            "/unitrusteeship",
            "/address",

            /* "/unit/switch"*/

/*            "/big_date/list",
            "/big_date/unit_date",*/
            //   "/device/switch",
            // "/pic/versions",


    };
    private static final String[] roleUrls = {"/tcp",
            "/set_model/list",//产品列表
            "/web/user_out"
    };  //不需要权限的接口

    @Autowired
    private PowerSyetemService powerSyetemService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

/*        if (httpServletRequest.getHeader(HttpHeaders.ORIGIN) != null) {
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://111.61.64.62:8002");
        }*/
        // httpServletResponse.setCharacterEncoding("UTF-8");
/*        HttpServletResponse res = (HttpServletResponse) httpServletResponse;
        res.setContentType("text/html;charset=UTF-8");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "0");
        res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("XDomainRequestAllowed","1");*/


/*        if (httpServletRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
            System.out.println("200执行");
            httpServletResponse.setStatus(200);
            return true;
        }*/


        String stringUrl = httpServletRequest.getRequestURL().toString().replaceAll(" ", "");
        //   logger.info(httpServletRequest.getRemoteHost());

        System.out.println(httpServletRequest.getRemoteHost());
        for (String allowUrl : allowUrls) {

            if (stringUrl.contains(allowUrl)) { //访问非限制接口 放行
                // System.out.println("放行");
                return true;
            }
        }

        //-----------------------------------需要登录才能访问的接口


        String token = CookieUtils.getCookieValue(httpServletRequest, "token", true);

        // String token2 = httpServletRequest.getParameter("token");
/*        System.out.println(token+"&&&&&&&&&&&&&&");
        System.out.println(token2+"&&&&&&&&&&&&&&");*/
        if (StringUtils.isEmpty(token)) {
            token = httpServletRequest.getParameter("token");
        }

        System.out.println(token);
        //  token = "啊";

        if (!StringUtils.isEmpty(token)) { //访问非限制接口 token中有用户信息

            ZhongkaiResult userToken = powerSyetemService.getUserToken(token); //取出用户数据

            if (userToken.getStatus() != 200) {  //登录状态过期

                this.returnJson(httpServletResponse, new Gson().toJson(userToken));

                return false;
            } else {

                //注意 缓存 更改用户数据时 擦除用户缓存数据 重新查询数据库
                // 1 查询结果等于200 缓存存在用户登录状态
                // 2 查看用户是否访问权限接口(提前定义用户接口)
                // 3 是访问的权限接口
                // 4 查询用户当前权限 权限内包含此接口 放行
                // 5 不包含此接口 返回权限不足  ArrayList<MenusRole> list

                //取出用户信息
                Chinaset chinaset = (Chinaset) userToken.getData();
//-----------------------------------需要登录但不需要权限就可以访问的接口

                for (String roleUrl : roleUrls) {
                    if (stringUrl.contains(roleUrl)) { //此为不需要权限的接口
                        httpServletRequest.setAttribute("user", chinaset);
                        return true; //放行
                    }
                }

//-----------------------------------需要登录和权限才能访问的接口


                ZhongkaiResult zhongkaiResult = powerSyetemService.queryRole(String.valueOf(chinaset.getSetRole())); //查询权限

                //  System.out.println(zhongkaiResult.getData());
                if (zhongkaiResult.getStatus() == 200) {

                    ArrayList<MenusRole> list = (ArrayList<MenusRole>) zhongkaiResult.getData();

                    for (MenusRole menusRole : list) {
                        // System.out.println(menusRole.getMenusByNumber().getmUrl());
                        // System.out.println(menusRole.getSetRoleById().getName());
                        if (stringUrl.contains(menusRole.getMenusByNumber().getmUrl())) {  //数据库中存在此url 放行
                            // System.out.println("存在");
                            httpServletRequest.setAttribute("user", chinaset);
                            return true;
                        }
                    }


                    this.returnJson(httpServletResponse, new Gson().toJson(ZhongkaiResult.build(1002, "权限不足")));
                    return false;
                }


                //  return true; //非需要验证权限的接口 放行


            }
        } else {

            this.returnJson(httpServletResponse, new Gson().toJson(ZhongkaiResult.build(400, "请先登录")));

            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }


    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
